package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.minio.MinIOTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {

    @Resource
    private Configuration configuration;

    @Resource
    private MinIOTemplate minIOTemplate;


    @Override
    public String buildArticleHtml2MinIo(Long id, String content) {
        String url = null;
        ByteArrayInputStream is =null ;
        try {
            //1.加载模板
            Template template = configuration.getTemplate("article.ftl");

            //2.准备数据模型
            Map<String,Object> dataModel=new HashMap<>();
            List<Map> maps = JSON.parseArray(content, Map.class);
            dataModel.put("content",maps);
            //3.生成静态HTML页面
            StringWriter sw=new StringWriter();
            template.process(dataModel,sw);
            //4.上传到MinIon中
            is=new ByteArrayInputStream(sw.toString().getBytes());
            url = minIOTemplate.uploadHtmlFile("", id + ".html", is);

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
